<?php

namespace addons\shopro\controller;

//use app\common\model\User;
use addons\epay\library\Service;
use addons\shopro\model\Dispatch;
use addons\shopro\model\DispatchSelfetch;
use addons\shopro\model\OrderItem;
use addons\shopro\model\User;
use addons\shopro\model\UserAddress;
use addons\shopro\model\Verify;
use addons\vip\model\Record;
use addons\shopro\model\Goods as GoodsModel;
use think\Db;
class Order extends Base
{

    protected $noNeedLogin = ['orderMoney'];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $params = $this->request->get();

        $this->success('订单列表', \addons\shopro\model\Order::getList($params));
    }

    /**
     * 发放分佣
     * @author li688
     * @date 2024/7/22  下午6:35
     * @notes
     */
    public function orderMoney()
    {
        $where = [];
        $where['order.status'] = ['in',[1,2]];
        $todayPrice = Db::name('shopro_order_item')->alias('item')
            ->join('shopro_order order', 'order.id = item.order_id')
            ->join('shopro_goods goods', 'goods.id = item.goods_id')
            ->where($where)
            ->whereTime('order.createtime', 'yesterday')
            ->where('find_in_set(:id,goods.category_ids)',['id'=>2])
            ->sum('item.pay_price')*0.1;
        if($todayPrice > 0){
            $vip1User = Db::name('user')->where('vip',1)->field('id')->select();//398会员数
            if($vip1User){
                $vip1Money = $todayPrice * 0.02/count($vip1User);//398会员每人应得佣金
                foreach ($vip1User as $v){
                    $log = Db::name('user_money_log')->where('user_id',$v['id'])->where('memo','每日分红')->whereTime('createtime', 'today')->find();
                    if(!$log) {
                        User::money($vip1Money, $v['id'], '1',0,'每日分红');
                    }
                }
            }
            $vip2User = Db::name('user')->where('vip',2)->field('id')->select();//1980会员数
            if($vip2User){
                $vip2Money = $todayPrice * 0.03/count($vip2User);//1980会员每人应得佣金
                foreach ($vip2User as $v){
                    $log = Db::name('user_money_log')->where('user_id',$v['id'])->where('memo','每日分红')->whereTime('createtime', 'today')->find();
                    if(!$log) {
//                        User::money($vip2Money, $v['id'], '每日分红', 1);
                        User::money($vip2Money, $v['id'], '1',0,'每日分红');
                    }
                }
            }
            $vip3User = Db::name('user')->where('vip',3)->field('id')->select();//6980会员数
            if($vip3User){
                $vip3Money = $todayPrice * 0.05/count($vip3User);//6980会员每人应得佣金
                foreach ($vip3User as $v){
                    //查询此用户今日是否已发过分佣
                    $log = Db::name('user_money_log')->where('user_id',$v['id'])->where('memo','每日分红')->whereTime('createtime', 'today')->find();
                    if(!$log){
//                        User::money($vip3Money,$v['id'],'每日分红',1);
                        User::money($vip3Money, $v['id'], '1',0,'每日分红');
                    }

                }
            }

        }
        echo '分红成功';
    }

    public function detail()
    {
        $params = $this->request->get();
        $this->success('订单详情', \addons\shopro\model\Order::detail($params));
    }


    public function itemDetail()
    {
        $params = $this->request->get();
        $this->success('订单商品', \addons\shopro\model\Order::itemDetail($params));
    }


    // 即将废弃
    public function statusNum()
    {
        $this->success('订单数量', \addons\shopro\model\Order::statusNum());
    }


    // 取消订单
    public function cancel()
    {
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'cancel');

        $this->success('取消成功', \addons\shopro\model\Order::operCancel($params));
    }

    // 删除订单
    public function delete()
    {
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'delete');

        $this->success('删除成功', \addons\shopro\model\Order::operDelete($params));
    }

    // 确认收货
    public function confirm()
    {
        repeat_filter();        // 防抖
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'confirm');

        $this->success('收货成功', \addons\shopro\model\Order::operConfirm($params));
    }


    public function comment()
    {
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'comment');

        $this->success('评价成功', \addons\shopro\model\Order::operComment($params));
    }


    public function pre()
    {
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'pre');

        $result = \addons\shopro\model\Order::pre($params);

        if (isset($result['msg']) && $result['msg']) {
            $this->error($result['msg'], $result);
        } else {
            $this->success('计算成功', $result);
        }
    }


    public function createOrder()
    {
        repeat_filter();        // 防抖
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'createOrder');

        $order = \addons\shopro\model\Order::createOrder($params);

        $this->success('订单添加成功', $order);
    }
    // 获取订单号
    public  function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return $order_sn . $id;
    }

    /**
     * 领取商品
     * @return void
     */
    public function receiveGoods()
    {
        $user = $this->auth->getUser();
        $goods_ids = $this->request->post('goods_id');
        $address_id = $this->request->post('address_id');
        $level = $this->request->post('level');
        $goods_arr = explode(',',$goods_ids);
        $vipInfo = \addons\vip\library\Service::getVipInfo();
        if(!$vipInfo){
            $this->error('您还不是会员');
        }
        if($vipInfo['level'] < $level){
            $this->error('信息错误');
        }
        $log = [];
        foreach ($goods_arr as $k=>$goods_id){
            $goods = GoodsModel::get($goods_id);
            if(!$goods){
                $this->error('商品不存在');
            }
            if(!$goods_id || !$level){
                $this->error('参数错误');
            }
            // $vip = Record::where('user_id', $user->id)->where('level',$level)->where('status','not in',['created','canceled'])->find();
            // if(!$vip){
            //     $this->error('数据错误');
            // }
            $is_log = Db::name('vip_receive')->where('user_id',$user->id)->where('level',$level)->where('goods_type',$goods->type)->find();
            if($is_log){
                $this->error('请勿重复领取');
            }
            // if($goods->type == 'virtual'){
            //     if($vip['is_virtual_receive'] != 0){
            //         $this->error('请勿重复领取');
            //     }
            // }else{
            //     if($vip['is_receive'] != 0){
            //         $this->error('请勿重复领取');
            //     }
            // }

            $user_address = UserAddress::get($address_id);
            if($goods->type != 'virtual' && !$user_address){
                $this->error('收货地址错误');
            }
            $orderData = [];
            $orderData['order_sn'] = $this->getSn($user->id);
            $orderData['user_id'] = $user->id;
            $orderData['type'] = 'goods';
            $orderData['activity_type'] = '';
            $orderData['goods_amount'] = $goods->price;
            $orderData['dispatch_amount'] = 0;
            $orderData['total_amount'] = 0;
            $orderData['score_amount'] = 0;
            $orderData['total_fee'] = 0;
            $orderData['discount_fee'] = 0;
            $orderData['score_fee'] = 0;          // 记录score 支付数
            $orderData['coupon_fee'] = 0;
            $orderData['activity_discount_money'] = 0;
            $orderData['dispatch_discount_money'] = 0;
            $orderData['goods_original_amount'] = 0;
            if ($user_address) {
                $orderData['phone'] = $user_address->phone;
                $orderData['consignee'] = $user_address->consignee;
                $orderData['province_name'] = $user_address->province_name;
                $orderData['city_name'] = $user_address->city_name;
                $orderData['area_name'] = $user_address->area_name;
                $orderData['address'] = $user_address->address;
                $orderData['province_id'] = $user_address->province_id;
                $orderData['city_id'] = $user_address->city_id;
                $orderData['area_id'] = $user_address->area_id;
            }
            $orderData['status'] = 1;
            $orderData['pay_type'] = 'vip';
            $orderData['remark'] = '领取商品';
            $orderData['ext'] = '';
            $order = new \addons\shopro\model\Order();
            $order->allowField(true)->save($orderData);

            $orderItem = new OrderItem();

            $orderItem->user_id = $user->id;
            $orderItem->order_id = $order->id;
            $orderItem->goods_id = $goods_id;
            $orderItem->goods_type = $goods->type;
            $orderItem->goods_sku_price_id = Db::name('shopro_goods_sku_price')->where('goods_id', $goods->id)->value('id');

            $orderItem->goods_title = $goods->title;
            $orderItem->goods_image =  $goods->image;
            $orderItem->goods_original_price = $goods->original_price;
            $orderItem->discount_fee = 0;        // 平均计算单件商品所享受的折扣
            $orderItem->pay_price = 0;        // 平均计算单件商品不算运费，算折扣时候的金额
            $orderItem->goods_price = $goods->price;
            $orderItem->goods_num =  1;
            $orderItem->goods_weight = 0;
            $orderItem->dispatch_status = $goods->type == 'virtual' ? 1 : 0;
            $orderItem->dispatch_fee = 0;
            $orderItem->dispatch_type = $goods->dispatch_type;
            $orderItem->dispatch_id =  $goods->dispatch_ids;
            $orderItem->store_id =  0;
            $orderItem->aftersale_status = 0;
            $orderItem->comment_status = 0;
            $orderItem->refund_status = 0;
            $orderItem->save();
            $log[] = [
                'user_id'=>$user->id,
                'level'=>$level,
                'createtime'=>time(),
                'goods_type'=>$goods->type,
                'goods_id'=>$goods->id,
            ];
            // if($goods->type == 'virtual'){
            //     if(count($goods_arr) == $k+1){
            //         //更新vip领取状态
            //         $vip = Record::where('user_id', $user->id)->where('level',$level)->where('status','not in',['created','canceled'])
            //             ->update(['is_virtual_receive'=>1,'receivetime'=>time(),'goods_id'=>$goods_id]);
            //     }
            // }else{
            //     //更新vip领取状态
            //     $vip = Record::where('user_id', $user->id)->where('level',$level)->where('status','not in',['created','canceled'])
            //         ->update(['is_receive'=>1,'receivetime'=>time(),'goods_id'=>$goods_id]);
            // }

            if($goods->type == 'virtual'){
                // 获取配送模板
                $dispatch = Dispatch::where('type', $goods->dispatch_type)->where('id', $orderItem->dispatch_id)->find();
                $type_ids = $dispatch['type_ids'] ?? '';
                $dispatch_selfetch_ids = explode(',', $type_ids);
                $dispatchSelfetch = DispatchSelfetch::where('id', 'in', $dispatch_selfetch_ids)
                    ->order('id', 'asc')->find();

                $expiretime = null;       // 核销券过期时间
                if ($dispatchSelfetch) {
                    if ($dispatchSelfetch['expire_type'] == 'day') {
                        $expire_day = $dispatchSelfetch['expire_day'] > 0 ? $dispatchSelfetch['expire_day'] : 0;
                        $expiretime = $expire_day ? (time() + ($expire_day * 86400)) : null;
                    } else {
                        $expiretime = $dispatchSelfetch['expire_time'] ?: null;
                    }
                }
                $verify = Db::name('shopro_verify')->insert([
                    'user_id'=>$user->id,
                    'type'=>'verify',
                    'code'=>Verify::getCode(),
                    'order_id'=>$order->id,
                    'order_item_id'=>$orderItem->id,
                    'expiretime'=>$expiretime,
                    'oper_id'=>0,
                    'is_vip'=>1,
                    'createtime'=>time(),
                ]);
            }
        }
        if($log){
            Db::name('vip_receive')->insertAll($log);
        }

        $this->success('领取成功', $order);
    }


    // 获取可用优惠券列表
    public function coupons()
    {
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'coupons');

        $coupons = \addons\shopro\model\Order::coupons($params);

        $this->success('获取成功', $coupons);
    }
}
